import axios from 'axios'
import { Toast } from 'vant'
// 根据环境不同引入不同api地址
import { baseApi } from '@/config'
import { clientId, clientSecret } from '../config/env.development'

import _ from 'lodash'
let encryption = window.btoa(clientId + ':' + clientSecret)
// 测试token
// let tokenStr = '27acc927-f5c9-4680-a528-70c48f9819b8'
let needLoadingRequestCount = 0 //当前正在请求的数量
let loadingInstance

function showLoading() {
  if (needLoadingRequestCount === 0 && !loadingInstance) {
    loadingInstance = Toast.loading({
      duration: 0,
      forbidClick: true,
      loadingType: 'spinner',
      message: '加载中...'
    })
  }
  needLoadingRequestCount++
}

function closeLoading() {
  setTimeout(() => {
    // 以服务的方式调用的 Loading 需要异步关闭
    needLoadingRequestCount--
    needLoadingRequestCount = Math.max(needLoadingRequestCount, 0) // 保证大于等于0
    if (needLoadingRequestCount === 0) {
      if (loadingInstance) {
        hideLoading()
      }
    }
  })
}
var hideLoading = _.debounce(() => {
  loadingInstance.close()
  loadingInstance = null
}, 300)
// create an axios instance
const service = axios.create({
  baseURL: baseApi, // url = base api url + request url
  //baseURL: "http://127.0.0.1:8888/",
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000 // request timeout
})

// request interceptor
let isRefreshing = false
let requests = []
function refreshToken() {
  return new Promise(resolve => {
    service({
      method: 'post',
      url: '/api-uaa/oauth/dingtalk/refreshToken',
      params: {
        refreshToken: JSON.parse(window.sessionStorage.getItem('ldjsc_refresh_token')),
        userId: JSON.parse(window.sessionStorage.getItem('ldjsc_user_id'))
      }
    })
      .then(res => {
        if (res && res.data.datas.access_token) {
          window.sessionStorage.setItem('ldjsc_access_token', JSON.stringify(res.data.datas.access_token))
          window.sessionStorage.setItem('ldjsc_refresh_token', JSON.stringify(res.data.datas.refresh_token))
          resolve({ flag: 1, ...res })
        }
      })
      .catch(err => {
        console.log(err)
      })
  })
}

// request拦截器 request interceptor
service.interceptors.request.use(
  config => {
    // 钉钉鉴权
    if (config.url.includes('https://open.bigmodel.cn/api/paas/v4/chat/completions')) {
      config.headers['Authorization'] = 'Bearer 2b031dd053e4012453db60dcdb204960.GORiSTovIeuJmqPJ'
      console.log(config.headers['Authorization'])
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  async response => {
    if (response.data.resp_code == '401') {
      if (!isRefreshing) {
        isRefreshing = true
        const res1 = await refreshToken()
        if (res1.flag) {
          Promise.resolve().then(() => {
            requests.forEach(cb => cb()) // 执行那些 刷新tokens时 被挂起的请求
            requests = []
          })
        }
        isRefreshing = false
      }
      // 为了保证401请求顺序执行
      return new Promise(resolve => {
        requests.push(() => {
          resolve(service(response.config))
        })
      })
    }
    return response
  },
  async error => {
    console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)

// respone拦截器
service.interceptors.response.use(
  response => {
    closeLoading()
    return Promise.resolve(response)
  },
  error => {
    closeLoading()
    console.log('err' + error)
    return Promise.reject(error)
  }
)

export default service
